﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iOak.Business.Users;
using iOak.Business.Security;

namespace iOak.Web.Modules
{
    public partial class ChangePasswordControl : System.Web.UI.UserControl
    {
        private UserService _userService = new UserService();
        private WorkAssistant _workassistant = new WorkAssistant();
        private EncryptionService _encryptionService = new EncryptionService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            var user = _workassistant.CurrentUser;
            lblUserName.Text = user.UserName;
        }

        protected void btnOk_Click(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                var user = _workassistant.CurrentUser;
                string saltkey = _encryptionService.CreateSaltKey(5);
                user.SaltKey = saltkey;
                user.PasswordHash = _encryptionService.CreatePasswordHash(txtNewPassword.Text, saltkey);
                _userService.Update(user);
                this.Parent.Page.ClientScript.RegisterStartupScript(Page.GetType(), "showWarnning", "$(document).ready(function(){jAlert('密码修改成功！');});", true);
            }
        }

        protected bool ValidateData()
        {
            var user = _workassistant.CurrentUser;
            if (!_userService.ValidateUser(user.UserName, txtPassword.Text))
            {
                this.Parent.Page.ClientScript.RegisterStartupScript(Page.GetType(), "showWarnning", "$(document).ready(function(){jAlert('原始密码输入错误！');});", true);
                txtNewPassword.Text = String.Empty;
                txtPassword.Text = String.Empty;
                txtRePassword.Text = String.Empty;
                return false;
            }
            return true;
        }
    }
}